﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;

namespace BPM.Web.Shared;

/// <summary>
/// 当前会话状态
/// </summary>
public record SessionState
{
    /// <summary>
    /// 获得/设置 是否显示 Footer 模板 默认 false
    /// </summary>
    public bool ShowFooter { get; set; }

    /// <summary>
    /// 获得/设置 是否右侧使用 Tab 组件 默认为 false 不使用
    /// </summary>
    public bool UseTabSet { get; set; }

    /// <summary>
    /// 获得/设置 当前用户权限相关信息
    /// </summary>
    public LoginOutput? Auths { get; set; }

    /// <summary>
    /// 获得/设置 访问菜单信息
    /// </summary>
    public List<MenuItem> Menus { get; set; } = new();

    /// <summary>
    /// 获得/设置 叶子菜单信息
    /// </summary>
    public List<MenuItem> Leaves { get; set; } = new();

    /// <summary>
    /// 内容变化事件，用于注册在布局组件，用于全局刷新
    /// </summary>
    public event EventHandler<bool>? FragmentChanged;

    /// <summary>
    /// 重新加载系统
    /// </summary>
    /// <param name="load">是否重载数据</param>
    public void Reload(bool load) => FragmentChanged?.Invoke(this, load);

    /// <summary>
    /// 通过用户名检查当前请求 Url 是否已授权方法
    /// </summary>
    /// <param name="role">验证角色</param>
    /// <param name="path">验证资源路径</param>
    /// <param name="tag">验证组件标记</param>
    /// <returns></returns>
    public bool Auhorizing(string role, string path, string tag)
    {
        if (Auths == null)
        {
            return false;
        }

        if (Auths.AdminType == 1)
        {
            return true;
        }

        var inRole = string.IsNullOrWhiteSpace(role) || (Auths.Roles?.Any(x => x.Name == role) ?? false);
        var inPath = string.IsNullOrWhiteSpace(path) || (Auths.AllPermissions?.Any(x => x.Contains(path, StringComparison.OrdinalIgnoreCase)) ?? false);
        var inTag = string.IsNullOrWhiteSpace(tag) || (Auths.Menus?.Any(x => x.Meta.Title == tag) ?? false);

        return inRole && inPath || inTag;
    }
}
